package com.example.test.service;
import com.example.test.entity.Cart;
import com.example.test.entity.Product;

import com.example.test.mapper.CartMapper;
import com.example.test.mapper.ProductMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CartItemMatchingService {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public List<Product> matchCartItems() {
       SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            List<Cart> carts = cartMapper.selectAll();
            List<Integer> cartItemIds = carts.stream()
                    .map(Cart::getItemId)
                    .collect(Collectors.toList());
            ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
            List<Product> products = productMapper.selectAll();
            List<Product> matchedItems = new ArrayList<>();
            for (Product product : products) {
                int productId=product.getId().intValue();
                if (cartItemIds.contains(productId)) {
                    matchedItems.add(product);
                }
            }
            return matchedItems;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
